package cn.kent.netty.base.byteBuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

/**
 * 测试 {@link io.netty.buffer.ByteBuf}
 * 通过定义参数 -Dio.netty.allocator.type={unpooled|pooled} 指定池化&非池化
 */
public class TestByteBuf {
    public static void main(String[] args) {
//        ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer(); // 堆内存
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(); // 直接内存
        System.out.println(buf.getClass());
        log(buf);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            sb.append("a");
        }
        buf.writeBytes(sb.toString().getBytes());
        log(buf);
    }

    protected static void log(ByteBuf buf) {
        int length = buf.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder sb = new StringBuilder(rows * 80 * 2)
                .append("read next: ").append(buf.readerIndex())
                .append(" wirte text:").append(buf.writerIndex())
                .append(" capacity:").append(buf.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(sb, buf);
        System.out.println(sb.toString());
    }
}
